﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;

namespace TestXNA
{
    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        SpriteFont font;
        Model myModel;
        float aspectRatio;

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            TouchPanel.EnabledGestures = GestureType.FreeDrag;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            System.Diagnostics.Debug.WriteLine("GamePage");
        }

        public String getMessage()
        {
            DateTime t = System.DateTime.Now + new TimeSpan(0, 0, 0, 0, App.ViewModel.ClockOffset);
            String now = System.DateTime.Now.ToString("hh:mm:ss.fff");
            return App.ViewModel.ClockOffset + " - " + now + " - " + t.ToString("hh:mm:ss.fff");
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.content to load your game content here
            font = this.contentManager.Load<SpriteFont>("gameFont");
            myModel = this.contentManager.Load<Model>("Model/p1_wedge");
            aspectRatio = SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.AspectRatio;

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        int sentido = 0;
        float modelRotation = 0.0f;
        int intentos = 0;

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
/*            modelRotation += (float)e.ElapsedTime.TotalMilliseconds *
                MathHelper.ToRadians(0.1f); */

//            float prePos = App.ViewModel.modelPosition.X;

            // Windows Phone Controls
            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gesture = TouchPanel.ReadGesture();
                if (gesture.GestureType == GestureType.FreeDrag)
                {
//                    player.Position += gesture.Delta;
                    App.ViewModel.modelPosition.X += (gesture.Delta.X * 3.0f);
                    // actualicemos la posición.
                    App.ViewModel.sync.SendPos(App.ViewModel.modelPosition.X);
                }
            }

            DateTime t = System.DateTime.Now + new TimeSpan(0, 0, 0, 0, App.ViewModel.ClockOffset);
            modelRotation = (float)t.Second + (float)(t.Millisecond / 1000.0f);
//            modelPosition.X = (float) (Math.Sin(modelRotation / 2.0f) + 1.0f) * 3600.0f / 2.0f;

            if (App.ViewModel.Posicion > 1 && (System.DateTime.Now - App.ViewModel.sync.requestTime).Seconds > 0) // sólo el primero envía mensajes
            {
                App.ViewModel.sync.RequestTime();
//                App.ViewModel.sync.SendTime();
                intentos++;
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);
            
            Matrix[] transforms = new Matrix[myModel.Bones.Count];
            myModel.CopyAbsoluteBoneTransformsTo(transforms);
            
            foreach (ModelMesh mesh in myModel.Meshes)
            {
                // This is where the mesh orientation is set, as well 
                // as our camera and projection.
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = transforms[mesh.ParentBone.Index] *
                        Matrix.CreateRotationY(modelRotation)
                        * Matrix.CreateTranslation(App.ViewModel.modelPosition);
                    effect.View = Matrix.CreateLookAt(App.ViewModel.cameraPosition,
                        App.ViewModel.cameraView, Vector3.Up);
//                        Vector3.Zero, Vector3.Up);
                    effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                        MathHelper.ToRadians(45.0f), aspectRatio,
                        1.0f, 10000.0f);
                }
                // Draw the mesh, using the effects set above.
                mesh.Draw();
            }

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            spriteBatch.DrawString(font, getMessage(),
                new Vector2(
                    SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.TitleSafeArea.X,
                    SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.TitleSafeArea.Y),
                Color.White);
            spriteBatch.End();
        }
    }
}